package cn.edu.imust.loginregisterdemo.upload;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Update {
    boolean b = false;
    static boolean a = true;
    String returnValue = "这是默认返回值，接口调用失败";

    public boolean httpPost(String time,String gps,String edit,String pic,File pic1,File pic2) throws JSONException {
        String stringUrl = "http://39.101.162.140:80/dbs/upload";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username","hzy630");
        jsonObject.put("time",time);
        jsonObject.put("gps",gps);
        jsonObject.put("edit",edit);
        jsonObject.put("pic","data:image/webp;base64," + pic);
        Thread thread = new Thread(() -> {
            try {
                NameValuePair pair = new BasicNameValuePair("pic", String.valueOf(jsonObject));
                List<NameValuePair> pairList = new ArrayList<>();
                pairList.add(pair);
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairList, "UTF-8");
                HttpPost httpPost = new HttpPost(stringUrl);
                httpPost.setEntity(entity);
                HttpClient httpClient = new DefaultHttpClient();
                HttpResponse response = httpClient.execute(httpPost);
                if (returnValue.equalsIgnoreCase("success"))
                    b = true;
                HttpEntity httpEntity1 = response.getEntity();
                InputStream inputStream = httpEntity1.getContent();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String result = "";
                String line = "";
                while (null != (line = bufferedReader.readLine())) {
                    result += line;
                }
                if (result.equalsIgnoreCase("success"))
                    b = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        thread.start();
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return b;
    }

}